package com.pateo.bjev.contacts.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;
import com.pateo.bjev.contacts.R;
import com.pateo.bjev.contacts.utils.CallUtils;
import com.pateo.bluetooth.logic.bean.ContactData;
import com.pateo.bluetooth.logic.bean.PhoneNumber;
import com.pateo.bluetooth.logic.util.Constants;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by pateo on 17-5-9.
 */

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ViewHolder> implements SectionIndexer{

    protected static final int TYPE_CLASS = 10001;
    protected static final int TYPE_CONTACT = 10002;

    /** 默认错误头部字母. **/
    private static final char ERROR_LETTER = '#';

    private Context mContext;

    protected List<ContactData> contacts = new LinkedList<>();

    /**
     * 添加字母之后的List
     */
    protected List<ItemObject> list = new ArrayList<>();
    /** 字母头位置标示map **/
    private final Map<Character,Integer> letterMap = new HashMap<>();
    /** error type **/
//    private List<ItemObject> errorTypeList = new ArrayList<>();
    SparseArray<Character> sectionArray = new SparseArray<>();


    public ContactAdapter(Context context, List<ContactData> contactDataList){
        this.mContext = context;
        if(contactDataList!=null){
            this.contacts = contactDataList;
            updateContactList(contactDataList);
        }
    }

    public void updateContactList(List<ContactData> contacts){
        if(contacts!=null){
            this.contacts = contacts;
            setContainerList();
        }else{
            this.contacts.clear();
            list.clear();
        }
        notifyDataSetChanged();
    }

    public char[] getLetters(){
        char[] re = new char[sectionArray.size()];
        for(int i=0;i<sectionArray.size();i++){
            re[i] = sectionArray.valueAt(i);
        }
        return re;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        ViewHolder vh;
        if(viewType == TYPE_CLASS){
            View view  = LayoutInflater.from(mContext).inflate(R.layout.contacts_letter_item_layout,parent,false);
            vh = new TypeViewHolder(view);
        }else{
            View view = LayoutInflater.from(mContext).inflate(R.layout.contacts_item_layout,parent,false);
            vh = new ViewHolder(view);
        }
        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        ItemObject item = list.get(position);
        if(holder instanceof TypeViewHolder && item.type == TYPE_CLASS){
            ((TypeViewHolder) holder).letterView.setText(item.item.toString());
        }else{
            ContactData data = (ContactData) item.item;
            holder.contact_name.setText(data.getName());
            holder.addPhoneList(data.getPhoneNumList());
        }
    }

    @Override
    public int getItemViewType(int position) {
        return list.get(position).type;
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @Override
    public Object[] getSections() {
        return letterMap.keySet().toArray();
    }

    @Override
    public int getPositionForSection(int i) {
        char group = (char) i;
        if(letterMap.containsKey(group)){
            return letterMap.get(group);
        }
        return 0;
    }

    @Override
    public int getSectionForPosition(int i) {
        ItemObject item = list.get(i);
        try{
            char sectiongroup = 0;
            if(item.type == TYPE_CLASS){
                sectiongroup = (char) item.item;
            }else{
                ContactData data = (ContactData) item.item;
                sectiongroup = getHeadLetter(data);
            }
           return sectionArray.indexOfValue(sectiongroup);
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    class ViewHolder extends RecyclerView.ViewHolder{

        TextView contact_name;
        LinearLayout phoneContainer;

        public ViewHolder(View itemView) {
            super(itemView);

            contact_name = (TextView) itemView.findViewById(R.id.contact_name);
            phoneContainer = (LinearLayout) itemView.findViewById(R.id.phone_container);
        }

        void addPhoneList(List<PhoneNumber> phoneNumbers){
            phoneContainer.removeAllViews();
            for(final PhoneNumber phoneNumber : phoneNumbers){
                LinearLayout line = null;
                if(phoneContainer.getChildCount()==0){
                    line = newLine();
                }else{
                    line = (LinearLayout) phoneContainer.getChildAt(phoneContainer.getChildCount()-1);
                    if(line.getChildCount() == 2){
                        line = newLine();
                    }
                }
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
                params.weight = 1;

                View view = LayoutInflater.from(mContext).inflate(R.layout.phone_item_layout,null);
                TextView phone_num = (TextView) view.findViewById(R.id.phone_num);
                phone_num.setText(phoneNumber.getNumber());

                ImageView phone_type = (ImageView) view.findViewById(R.id.phone_type);
                if(phoneNumber.getType() == Constants.PHONE_TYPE_COMPANY){
                    phone_type.setImageResource(R.drawable.phone_company);
                }else if(phoneNumber.getType() == Constants.PHONE_TYPE_HOME){
                    phone_type.setImageResource(R.drawable.phone_home);
                }else if(phoneNumber.getType() == Constants.PHONE_TYPE_MOBILE){
                    phone_type.setImageResource(R.drawable.phone_mobile);
                }else{
                    phone_type.setImageResource(R.drawable.phone_other);
                }

                line.addView(view,params);

                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        CallUtils.call(mContext,phoneNumber.getNumber());
                    }
                });

                LinearLayout.LayoutParams lineParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);

                if(phoneContainer.getChildAt(0) != line){
                    lineParams.topMargin = 20;
                }

                phoneContainer.updateViewLayout(line,lineParams);
            }
            phoneContainer.setGravity(Gravity.CENTER_VERTICAL);
            LinearLayout.LayoutParams containerParam = (LinearLayout.LayoutParams) phoneContainer.getLayoutParams();
            containerParam.gravity = Gravity.CENTER_VERTICAL;
            containerParam.bottomMargin = 20;
            containerParam.topMargin = 20;
        }

        LinearLayout newLine(){
            LinearLayout line = new LinearLayout(mContext);
            line.setOrientation(LinearLayout.HORIZONTAL);
            phoneContainer.addView(line);
            return line;
        }

    }

    class TypeViewHolder extends ViewHolder{

        TextView letterView;

        public TypeViewHolder(View itemView) {
            super(itemView);
            letterView  = (TextView) itemView.findViewById(R.id.letter);
        }
    }

    protected void setContainerList(){
        if(!list.isEmpty()){
            list.clear();
        }
        if(!letterMap.isEmpty()){
            letterMap.clear();
        }

        char letter = ERROR_LETTER;
        int index = 0;
        int sectionIndex = 0;
        sectionArray.put(sectionIndex,ERROR_LETTER);
        sectionIndex++;
        for(ContactData data : contacts){
            char l = getHeadLetter(data);
            if(l!=letter && l!=ERROR_LETTER){
                sectionArray.put(sectionIndex++,l);
                letter = l;
                ItemObject item_type =new ItemObject(TYPE_CLASS,l);
                list.add(item_type);
                letterMap.put(letter,index++);
            }
            ItemObject item_data = new ItemObject(TYPE_CONTACT,data);
            list.add(item_data);
            index++;
        }
    }

    class ItemObject{
        Object item;
        int type;

        public ItemObject(int type,char head){
            item = head;
            this.type = type;
        }

        public ItemObject(int type,ContactData data){
            item = data;
            this.type = type;
        }
    }

    private char getHeadLetter(ContactData data){
        String headStr = data.getPinYinHead();
        if(TextUtils.isEmpty(headStr)){
            return ERROR_LETTER;
        }
        return headStr.charAt(0);
    }
}
